<template>
  <div>
    <span style="display:none">{{srcUrl}}</span>
    <div ref="wavesurfer" :id="wavesurferId"></div>
    <p v-show="!playShow && showNoUse" class="nouse-audio">{{$t('call.audioFailOrIng')}}</p>
    <div class="wave-detail-box">
      <i v-show="playShow" class="iconfont icon-baochi audio-icon" :class="isplay?'icon-huifu':''" @click="playOrPause"></i>
      <span v-show="playShow">{{timeStr}}</span>
    </div>
  </div>
</template>
<script>
  const WaveSurfer = require('wavesurfer.js')
  import {getCallTimeLength} from '@/utils/m7Utils.js'
  let clearInter
  let timeNumber
  export default {
    name: 'wavesurfer',
    props: {
      audioSpeed: Number,
      srcUrl: String,
      callStatus: String,
      isAutoPlay: Boolean,
      wavesurferId: {type: String, default: 'wavesurfer'}
    },
    data () {
      return {
        showNoUse: true,
        wavesurfer: {},
        isplay: true,
        timeStr: '00:00:00/00:00:00',
        currentTime: 0,
        allTime: 0,
        playShow: true
      }
    },
    mounted: function () {
      this.changeMave()
    },
    methods: {
      getLastTime (time1, time2) {
        if (!this.$store.state.call.SoundrecordingCard.visible && time1 > 0){
          this.$store.commit('call/CALL_SOUNDRECORDINGCARD_CURRENTTIME', time1)
        }
        return getCallTimeLength(time1) + '/' + getCallTimeLength(time2)
      },
      pauseAudio (flag) {
        this.wavesurfer.pause()
        this.isplay = true
      },
      playOrPause () {
        this.wavesurfer.playPause()
        this.isplay = !this.isplay
        this.$store.commit('call/CALL_SOUNDRECORDINGCARD_ISPLAY', this.isplay)
        this.$emit('pauseRecord',this.wavesurfer.isPlaying())
      },
      closeDial () {
        let pane = document.getElementById(this.wavesurferId)
        if (pane) {
          pane.innerHTML = ''
        }
        if (this.wavesurfer && this.wavesurfer.container) { // 解决第一次加载没有实体，直接调用方法报错导致绘图失败
          this.wavesurfer.destroy()// 删除事件、元素并断开WebAudio节点。
        }
      },
      changeMave () {
        if (this.srcUrl) {
          let pane = document.getElementById(this.wavesurferId)
          if (!this.wavesurferId || !pane) {
            return false
          }
          const option = {
            container: document.getElementById(this.wavesurferId),
            waveColor: '#878787',
            progressColor: '#459ae9',
            cursorColor: '#459ae9',
            splitChannels: true,
            hideScrollbar: true,
            maxCanvasWidth: 500,
            height: 40,
            barHeight: 3,
            pixelRatio: 1,
            backend: 'MediaElement'
          }
          const self = this
          this.wavesurfer = new WaveSurfer(option)
          this.wavesurfer.init()
          this.wavesurfer.load(this.srcUrl)
          // this.wavesurfer.playPause()
          let step = 1
          if (this.audioSpeed === 0.5) {
            step = 0.8
            this.wavesurfer.setPlaybackRate(0.8)
          } else if (this.audioSpeed === 0.75) {
            step = 0.9
            this.wavesurfer.setPlaybackRate(0.9)
          } else if (this.audioSpeed === 1.25) {
            step = 1.2
            this.wavesurfer.setPlaybackRate(1.2)
          } else if (this.audioSpeed === 1.5) {
            step = 1.3
            this.wavesurfer.setPlaybackRate(1.3)
          } else if (this.audioSpeed === 1.75) {
            step = 1.5
            this.wavesurfer.setPlaybackRate(1.5)
          } else if (this.audioSpeed === 2) {
            step = 1.6
            this.wavesurfer.setPlaybackRate(1.6)
          } else {
            this.wavesurfer.setPlaybackRate(this.audioSpeed)
          }
          this.wavesurfer.on('ready', function () {
            timeNumber = Math.ceil(1000 / step)
            clearInter = setInterval(() => {
              self.currentTime = Math.round(self.wavesurfer.getCurrentTime() || 0)
              self.timeStr = self.getLastTime(self.currentTime, self.allTime)
            }, timeNumber)
            let timer = self.wavesurfer.getDuration()
            self.allTime = timer || 0
            self.playShow = true
            self.showNoUse = true
            self.$emit('callAllTimeLess', false)
            self.$emit('showOldAudio', false)
            console.log(self.$store.state.call)
            if (self.$store.state.call.SoundrecordingCard.visible) {
              self.wavesurfer.skip(self.$store.state.call.SoundrecordingCard.currentTime)
            }
            self.isplay = true
            if (self.isAutoPlay) { // 是否自动播放
              self.wavesurfer.play()
              self.isplay = false
            } else {
              self.wavesurfer.pause()
              self.isplay = true
            }
          })
          this.wavesurfer.on('error', function () { // 录音加载失败时，就销毁绘图 && 提示无效录音 && 隐藏播放按钮
            self.closeDial()
            self.playShow = false
            if (self.callStatus && (self.callStatus === 'voicemail' || self.callStatus === 'dealing')) { // 录音加载失败时，若是已留言或者是已接听的有效录音地址，就放原生的audio
              self.$emit('showOldAudio', true) // 展示原生的audio
              self.showNoUse = false
            } else {
              self.$emit('showOldAudio', false)
              self.showNoUse = true
            }
            self.$emit('callAllTimeLess', true) // 隐藏多倍速按钮
            console.log('======加载录音失败哒======')
          })
          this.wavesurfer.on('finish', function () { // 录音播放完毕时
            console.log('======录音播放完毕啦======')
            self.isplay = true
            self.$store.commit('call/CALL_SOUNDRECORDINGCARD_ISPLAY', true)
          })
        }
      }
    },
    watch: {
      audioSpeed () {
        if (this.wavesurfer && this.wavesurfer.container && this.wavesurfer.mediaContainer) {
          // 解决wavesurfer.js插件里的this.media.playbackRate报错，声纹的音频还没有加载到，设置倍速报错的问题，无法复现操作，根据日志判断音频加载有问题
          if (this.audioSpeed === 0.5) {
            this.wavesurfer.setPlaybackRate(0.8)
            timeNumber = Math.ceil(1000 / 0.8)
          } else if (this.audioSpeed === 0.75) {
            this.wavesurfer.setPlaybackRate(0.9)
            timeNumber = Math.ceil(1000 / 0.9)
          } else if (this.audioSpeed === 1.25) {
            this.wavesurfer.setPlaybackRate(1.2)
            timeNumber = Math.ceil(1000 / 1.2)
          } else if (this.audioSpeed === 1.5) {
            timeNumber = Math.ceil(1000 / 1.3)
          } else if (this.audioSpeed === 1.75) {
            this.wavesurfer.setPlaybackRate(1.5)
            timeNumber = Math.ceil(1000 / 1.5)
          } else if (this.audioSpeed === 2) {
            this.wavesurfer.setPlaybackRate(1.6)
            timeNumber = Math.ceil(1000 / 1.6)
          } else {
            this.wavesurfer.setPlaybackRate(this.audioSpeed)
            timeNumber = Math.ceil(1000 / this.audioSpeed)
          }
        }
      },
      srcUrl () {
        this.closeDial() // 更换url的时候先清空原来的，再重新画波纹
        this.currentTime = 0
        this.allTime = 0
        clearInterval(clearInter) // 切换的时候先清除之前的定时器，否则会累加
        this.changeMave()
      }
    },
    activated () { // keep-alive 组件激活时调用时
      this.isplay = true // 解决播放ing切换到其他模块，再次进来时播放器状态不对的问题
    },
    beforeDestroy () {
      this.closeDial() // 组件被销毁的时候，把音频也销毁
      clearInterval(clearInter) // 销毁的时候去除定时器
    }
  }
</script>
<style lang="stylus" scoped>
  .wave-detail-box
    position absolute
    left 0px
    bottom 4px
    span
     display inline-block
     padding-top 3px
     line-height 16px
  .nouse-audio
    line-height 36px
  .audio-icon
    border 1px solid #459ae9
    border-radius 50%
    margin-right 6px
    width 20px
    height 20px
    line-height 19px
    cursor pointer
    font-size 12px
    text-align center
    color #459ae9
    box-sizing border-box
    display inline-block
    float left
</style>
